<template>
	<view class="charts-box">
	  <qiun-data-charts 
		v-if="isDataReady"
		type="line"
		:opts="chartOpts"
		:chartData="formatChartData"
	  />
	</view>
</template>
  
<script>
export default {
	name: 'LineChart',
	props: {
		// 图表数据
		data: {
			type: Array,
			required: true,
			default: () => []
		},
		// x轴数据
		categories: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			isDataReady: false,
			// 图表配置
			chartOpts: {
				color: ["#EE6666","#91CB74","#FAC858","#1890FF","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
				padding: [15, 10, 0, 15],
				enableScroll: false,
				dataLabel: false,
				legend: {
					show: true,
					position: 'bottom',
					float: 'left',
					padding: 10,
					margin: 5,
					itemGap: 10,
					fontSize: 13,
					lineHeight: 25,
					backgroundColor: 'rgba(0,0,0,0)',
					fontColor: '#666666',
					borderColor: 'rgba(0,0,0,0)',
					itemWidth: 20,
					itemHeight: 10,
					itemRadius: 5
				},
				xAxis: {
					disableGrid: true,
					labelCount: 3 // 
				},
				yAxis: {
					gridType: "dash",
					dashLength: 2,
					splitNumber: 5,
					axisLine: true,
					axisLineColor: '#CCCCCC',
					calibration: true,
					fontSize: 10
				},
				extra: {
					line: {
						type: "curve",
						width: 2,
						activeType: "hollow"
					}
				}
			}
		}
	},
	watch: {
		data: {
			handler(newVal) {
				console.log('Data changed:', newVal);
				this.checkDataReady();
			},
			immediate: true,
			deep: true
		},
		categories: {
			handler(newVal) {
				console.log('Categories changed:', newVal);
				this.checkDataReady();
			},
			immediate: true,
			deep: true
		}
	},
	methods: {
		checkDataReady() {
			const hasData = Array.isArray(this.data) && this.data.length > 0;
			const hasCategories = Array.isArray(this.categories) && this.categories.length > 0;
			this.isDataReady = hasData && hasCategories;
			console.log('Data ready status:', this.isDataReady, 'Data:', this.data, 'Categories:', this.categories);
		}
	},
	computed: {
		formatChartData() {
			if (!Array.isArray(this.data)) return { series: [] }
			
			// 确保数据格式正确
			const displayData = this.data.map(item => {
				// 确保每个数据项都有必要的属性
				return {
					name: item.name || '',
					data: Array.isArray(item.data) ? item.data : [0]
				}
			});
			
			// 确保categories是数组
			const categories = Array.isArray(this.categories) ? this.categories : [];
			
			return {
				categories: categories,
				series: displayData
			}
		}
	}
}
</script>
  
<style scoped>
.charts-box {
	width: 100%;
	height: 250px;
	padding-top: 30px;
}
</style>